// presentation/screens/AnalysisScreen.kt
package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.hwpt.chesedemo.presentation.component.ChessPiece
import com.hwpt.chesedemo.presentation.component.Position
import com.hwpt.chesedemo.presentation.theme.strings
import com.hwpt.chesedemo.presentation.viewmodel.AnalysisItem
import com.hwpt.chesedemo.presentation.viewmodel.AnalysisViewModel
import com.hwpt.chesedemo.presentation.viewmodel.InputMethod
import com.hwpt.chesedemo.presentation.viewmodel.MoveNavigation

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AnalysisScreen(
    navController: NavController,
    viewModel: AnalysisViewModel = hiltViewModel()
) {
    val gradient = Brush.verticalGradient(
        colors = listOf(Color(0xFF6A11CB), Color(0xFF2575FC))
    )

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = strings().review,
                        color = Color.White
                    )
                },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = strings().back,
                            tint = Color.White
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(gradient)
                .padding(paddingValues)
        ) {
            AnalysisContent(viewModel)
        }
    }
}

@Composable
fun AnalysisContent(viewModel: AnalysisViewModel) {
    val state = viewModel.state
    val scrollState = rememberScrollState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(scrollState)
            .padding(16.dp)
    ) {
        // 输入方法选择
        InputMethodSection(
            selectedMethod = state.selectedInputMethod,
            onMethodSelected = viewModel::onInputMethodSelected
        )

        Spacer(modifier = Modifier.height(16.dp))

        when (state.selectedInputMethod) {
            InputMethod.RECORD -> {
                GameRecordsSection(
                    records = state.gameRecords,
                    selectedRecord = state.selectedRecord,
                    onRecordSelected = viewModel::onRecordSelected
                )
            }
            InputMethod.TEXT -> {
                TextInputSection(
                    pgnText = state.pgnText,
                    onTextChanged = viewModel::onPgnTextChanged
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        AnalyzeButton(
            enabled = state.isAnalyzeEnabled,
            isLoading = state.isLoading,
            onAnalyze = viewModel::onAnalyze
        )

        if (state.isLoading) {
            Spacer(modifier = Modifier.height(16.dp))
        }

        if (state.showChessboard) {
            Spacer(modifier = Modifier.height(24.dp))
            ChessboardSection(
                boardState = state.currentBoardState,
                currentMoveIndex = state.currentMoveIndex,
                totalMoves = state.moves.size,
                onMoveNavigation = viewModel::onMoveNavigation
            )
        }

        if (state.showAnalysis) {
            Spacer(modifier = Modifier.height(24.dp))
            AnalysisSection(
                analysisItems = state.analysisResults,
                highlightedIndex = state.highlightedMoveIndex,
                onAnalysisItemSelected = viewModel::onAnalysisItemSelected
            )
        }
    }
}

@Composable
fun MethodButton(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Button(
        onClick = onClick,
        modifier = modifier,
        colors = ButtonDefaults.buttonColors(
            containerColor = if (isSelected) {
                Color.White.copy(alpha = 0.4f)
            } else {
                Color.White.copy(alpha = 0.2f)
            }
        ),
        elevation = ButtonDefaults.buttonElevation(
            defaultElevation = if (isSelected) 8.dp else 4.dp,
            pressedElevation = 12.dp
        )
    ) {
        Text(
            text = text,
            color = Color.White,
            fontSize = 14.sp
        )
    }
}
@Composable
fun ChessboardSection(
    boardState: List<List<ChessPiece?>>,
    currentMoveIndex: Int,
    totalMoves: Int,
    onMoveNavigation: (MoveNavigation) -> Unit,
    highlightedMove: Pair<Position, Position>? = null
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.15f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "♟️",
                    fontSize = 20.sp,
                    modifier = Modifier.padding(end = 8.dp)
                )
                Text(
                    text = strings().gameDetails,
                    color = Color.White,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 为复盘模式创建简化的ChessBoard调用
            com.hwpt.chesedemo.presentation.component.ChessBoard(
                boardState = boardState,
                selectedPiece = null, // 复盘模式下不选择棋子
                validMoves = emptyList(), // 复盘模式下不显示有效移动
                highlightedMove = highlightedMove, // 传递高亮移动参数
                onPieceSelected = { _, _ ->
                    // 复盘模式下点击棋子不做任何操作
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
            )

            Spacer(modifier = Modifier.height(16.dp))

            MoveControls(
                currentMoveIndex = currentMoveIndex,
                totalMoves = totalMoves,
                onMoveNavigation = onMoveNavigation
            )
        }
    }
}

@Composable
fun MoveControls(
    currentMoveIndex: Int,
    totalMoves: Int,
    onMoveNavigation: (MoveNavigation) -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Button(
            onClick = { onMoveNavigation(MoveNavigation.FIRST) },
            enabled = currentMoveIndex > 0,
            modifier = Modifier.weight(1.2f),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f),
                disabledContainerColor = Color.White.copy(alpha = 0.1f)
            )
        ) {
            Text(text = "|◀", color = Color.White)
        }
        Button(
            onClick = { onMoveNavigation(MoveNavigation.PREVIOUS) },
            enabled = currentMoveIndex > 0,
            modifier = Modifier.weight(1f),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f),
                disabledContainerColor = Color.White.copy(alpha = 0.1f)
            )
        ) {
            Text(text = "◀", color = Color.White)
        }

        Box(
            modifier = Modifier
                .weight(1f)
                .align(Alignment.CenterVertically),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "${currentMoveIndex}/${totalMoves}",
                color = Color.White,
                fontSize = 14.sp
            )
        }

        Button(
            onClick = { onMoveNavigation(MoveNavigation.NEXT) },
            enabled = currentMoveIndex < totalMoves,
            modifier = Modifier.weight(1f),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f),
                disabledContainerColor = Color.White.copy(alpha = 0.1f)
            )
        ) {
            Text(text = "▶", color = Color.White)
        }
        Button(
            onClick = { onMoveNavigation(MoveNavigation.LAST) },
            enabled = currentMoveIndex < totalMoves,
            modifier = Modifier.weight(1.2f),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f),
                disabledContainerColor = Color.White.copy(alpha = 0.1f)
            )
        ) {
            Text(text = "▶|", color = Color.White)
        }
    }
}

@Composable
fun AnalysisSection(
    analysisItems: List<AnalysisItem>,
    highlightedIndex: Int,
    onAnalysisItemSelected: (Int) -> Unit
) {
    val listState = rememberLazyListState()

    // 当高亮索引变化时，自动滚动到对应位置
    LaunchedEffect(highlightedIndex) {
        if (analysisItems.isNotEmpty() && highlightedIndex in analysisItems.indices) {
            listState.animateScrollToItem(highlightedIndex)
        }
    }

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.15f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "🤖",
                    fontSize = 20.sp,
                    modifier = Modifier.padding(end = 8.dp)
                )
                Text(
                    text = strings().analysisResults,
                    color = Color.White,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.height(12.dp))

            if (analysisItems.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = strings().noGameRecords,
                        color = Color.White.copy(alpha = 0.7f)
                    )
                }
            } else {
                // 显示当前高亮状态提示
                val currentHighlightedItem = if (highlightedIndex in analysisItems.indices) {
                    analysisItems[highlightedIndex]
                } else {
                    analysisItems.firstOrNull()
                }

                currentHighlightedItem?.let { item ->
                    Text(
                        text = "${strings().turn}: ${item.moveNumber}${if (item.isWhiteMove) "." else "..."} ${item.move}",
                        color = Color.Yellow.copy(alpha = 0.9f),
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                }

                LazyColumn(
                    modifier = Modifier.height(300.dp),
                    state = listState
                ) {
                    itemsIndexed(analysisItems) { index, item ->
                        AnalysisItemView(
                            item = item,
                            isHighlighted = index == highlightedIndex,
                            onClick = { onAnalysisItemSelected(index) }
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun AnalysisItemView(
    item: AnalysisItem,
    isHighlighted: Boolean,
    onClick: () -> Unit
) {
    val backgroundColor = if (isHighlighted) {
        Color.Yellow.copy(alpha = 0.3f)
    } else {
        Color.Transparent
    }

    val borderColor = if (isHighlighted) {
        Color.Yellow
    } else {
        Color.Transparent
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .background(backgroundColor)
            .border(2.dp, borderColor)
            .clickable(onClick = onClick)
            .padding(12.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "${item.moveNumber}${if (item.isWhiteMove) "." else "..."} ${item.move}",
                color = if (isHighlighted) Color.Yellow else Color.White,
                fontWeight = FontWeight.Bold,
                fontSize = 16.sp
            )
            if (isHighlighted) {
                Spacer(modifier = Modifier.size(8.dp))
                Text(
                    text = "👆 ${strings().turn}",
                    color = Color.Yellow,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = item.analysis,
            color = if (isHighlighted) Color.White else Color.White.copy(alpha = 0.9f),
            fontSize = 14.sp,
            lineHeight = 18.sp
        )
    }
}

